package com.example.study.page.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.study.databinding.MovieItemBinding
import com.example.study.source.Movie
import com.squareup.picasso.Picasso

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
class CustomPagingDataAdapter :
    PagingDataAdapter<Movie, CustomPagingDataAdapter.CustomViewHolder>(diffCallback = DiffCallback()) {

    class DiffCallback : DiffUtil.ItemCallback<Movie>() {
        override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean {
            return oldItem.title == newItem.title
        }

        override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean {
            return oldItem == newItem
        }

    }

    inner class CustomViewHolder(private val binding: MovieItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
        @SuppressLint("SetTextI18n")
        fun bind(movie: Movie) {
            binding.title.text = movie.title
            binding.year.text = "year " + movie.year.toString()
            movie.image?.small?.let {
                Picasso.get().load(it).into(binding.imageView)
            }
        }
    }

    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        getItem(position)?.let { holder.bind(it) }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
        val binding = MovieItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return CustomViewHolder(binding)
    }
}